package com.cari.oa.controller;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class VeriCodeController {

    private static char[] seq = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    public static final String VERI_CODE_ATTR = "vericode";
    private static final Logger logger = LoggerFactory.getLogger(VeriCodeController.class);

    @RequestMapping("/vericode.do")
    public void generate(HttpServletRequest request, HttpServletResponse response) {
        try {
            randomImage(request.getSession(), response.getOutputStream());
        } catch (IOException e) {
            logger.error("生成验证码错误", e);
        }
    }
    
    private String randomImage(HttpSession session, OutputStream os)
            throws ImageFormatException, IOException {
        Random r = new Random();

        int WIDTH = 70;
        int HEIGHT = 30;
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, 1);

        Graphics g = image.getGraphics();
        g.setColor(new Color(203, 250, 254));
        g.fillRect(0, 0, WIDTH, HEIGHT);
        
        for (int i = 0; i <= 10; i++) {
            g.setColor(randomColor(r));
            g.drawLine(r.nextInt(WIDTH), r.nextInt(HEIGHT), r.nextInt(WIDTH), r.nextInt(HEIGHT));
        }
        
        g.setColor(new Color(0, 0, 0));

        StringBuilder number = new StringBuilder();

        int NUM = 4;
        for (int i = 0; i < NUM; i++) {
            g.setColor(new Color(0, 0, 0));
            int h = (int) (HEIGHT * 60 / 100 * 0.7D + HEIGHT * 30 / 100);
            g.setFont(new Font(null, 3, h));
            String ch = String.valueOf(seq[r.nextInt(seq.length)]);
            number.append(ch);
            g.drawString(ch, i * WIDTH / NUM * 90 / 100, h);
        }

        session.setAttribute(VERI_CODE_ATTR, number.toString());

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
        encoder.encode(image);
        os.flush();

        return number.toString();
    }

    private Color randomColor(Random r) {
        return new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
    }
}